package com.qijian.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qijian.common.utils.DateUtils;
import com.qijian.common.utils.StringUtils;
import com.qijian.system.domain.UserExtra;
import com.qijian.system.mapper.UserExtraMapper;
import com.qijian.system.service.ISysConfigService;
import com.qijian.system.service.IUserExtraService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 用户额外信息Service业务层处理
 *
 * @author qijian
 * @date 2024-07-31
 */
@Service
@RequiredArgsConstructor
public class UserExtraServiceImpl extends ServiceImpl<UserExtraMapper, UserExtra> implements IUserExtraService {

    private final UserExtraMapper userExtraMapper;


    @Autowired
    private ISysConfigService configService;

    @Override
    public void resetClientId(Long userId, String clientId) {

        userExtraMapper.resetClientId(userId,clientId);
    }

    @Async
    @Override
    public void recordLoginInfo(Long userId, String clientId,String ip) {

        String flag = configService.selectConfigByKey("system.enableRecordLoginInfo");

        if (null == flag || "N".equals(flag)) {
            return;
        }


        Random random = new Random();
        try {
            int randomMillis = random.nextInt(3000);
            TimeUnit.MILLISECONDS.sleep(randomMillis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt(); // 重置中断状态
        }

        UserExtra userExtra = new UserExtra();
        userExtra.setUserId(userId);
        userExtra.setLoginIp(ip);
        userExtra.setLastLoginTime(DateUtils.dateTimeNow());
        userExtra.setLoginDate(DateUtils.getNowDate());
        if (StringUtils.isNotEmpty(clientId)) {
            userExtra.setClientId(clientId);
        }
        this.saveOrUpdate(userExtra);

        if (StringUtils.isNotEmpty(clientId)) {
            // if multiple users share the  same client  set others to null
            this.resetClientId(userId, clientId);
        }

    }
}
